﻿using General.Core.Config;
using General.Entities.Data;
using General.Framework;
using General.Mvc.Filters;
using General.Services.Template;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace General.Mvc.Controllers.Admin
{
    [Route("api/admin/[controller]/[action]")]
    [ApiController]
    [ServiceFilter(typeof(ResponseLogTimeFilter))]
    public class TemplateController : Controller
    {
        private readonly ITemplateService templateService;
        private readonly IMemoryCache memoryCache;

        public TemplateController(ITemplateService templateService,
             IMemoryCache memoryCache)
        {
            this.templateService = templateService;
            this.memoryCache = memoryCache;
        }




        /// <summary>
        /// 获取所有模板页面
        /// </summary>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> GetTemplatePages()
        {
            return Content(JsonHelper.Serialize(templateService.GetTemplatePages()));
        }

        /// <summary>
        /// 设置模板
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> SetTemplateName([FromForm]string templateSelect)
        {
            var res = await templateService.SetTemplateName(templateSelect);

            if (res > 0)
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "修改成功！" }));
            }
            else
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Fail, message = "出现错误！" }));
            }
        }



        /// <summary>
        /// 显示代码编辑器
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> ShowCodeEditer([FromServices] IWebHostEnvironment environment, string fileName)
        {
            var templatePages = WebSiteTemplateConfig.GetTemplatePages();
            if (templatePages.Where(x=>x.name == fileName).FirstOrDefault() == null)
            {
                return Content("打开的错误文件,请联系系统管理员!");
            }
            string webRootPath = environment.WebRootPath;
            var currentName = memoryCache.Get(WebSiteConfig.WEBSITE_TEMPLATENAME_STRING);
            var filePath = webRootPath + WebSiteConfig.WEBSITE_TEMPLATENAME_PATH + currentName + "/" + fileName;
            var fileContent = string.Empty;
            //判断文件是否存在
            if (System.IO.File.Exists(filePath))
            {
                fileContent = await System.IO.File.ReadAllTextAsync(filePath);
            }
            else
            {
                using (System.IO.File.Create(filePath)) //必须释放
                {

                }
            }
            ViewBag.fileName = fileName;
            return View("/Views/Admin/CodeEditer.cshtml", fileContent);
        }


        /// <summary>
        /// 编辑模板文件
        /// </summary>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> EditTemplateInfo([FromServices] IWebHostEnvironment environment, [FromForm]string name,[FromForm]string content)
        {
            var templatePages = WebSiteTemplateConfig.GetTemplatePages();
            if (templatePages.Where(x => x.name == name).FirstOrDefault() == null)
            {
                return Content("保存失败,请联系系统管理员!");
            }
            string webRootPath = environment.WebRootPath;
            var currentName = memoryCache.Get(WebSiteConfig.WEBSITE_TEMPLATENAME_STRING);
            var filePath = webRootPath + WebSiteConfig.WEBSITE_TEMPLATENAME_PATH + currentName + "/" + name;
            await System.IO.File.WriteAllTextAsync(filePath, content);
           
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "保存成功！" })); ;
        }
    }
}
